package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 开始时间戳
     */
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    /**
     * 位置
     */
    private static final int COUNT_BITS = 32;
    public long nextId(String keyPrefix){
        LocalDateTime now = LocalDateTime.now();
        //获取现在的秒数
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        ////生成时间戳
        long timeStamp = nowSecond - BEGIN_TIMESTAMP;

        //生成序列号
        //获取当前时间
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增长
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        //拼接并返回
        //先向左移到合适的位置，后面的用0补齐，并用或运算
        return timeStamp<<COUNT_BITS | count;
    }


}
